package com.dm.cloud.utils;

import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import lombok.extern.log4j.Log4j2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 利用jodconverter(基于OpenOffice服务)将文件(*.doc、*.docx、*.xls、*.ppt)转化为html格式或者pdf格式，
 * 使用前请检查OpenOffice服务是否已经开启, OpenOffice进程名称：soffice.exe | soffice.bin
 *
 * @author yjclsx
 */
@Log4j2
public class Doc2PDFUtil {

    private static Doc2PDFUtil doc2HtmlUtil;
    private static String TARGET_FOLDER = "F:\\OpenOffice\\files\\";
    /**
     * 获取Doc2HtmlUtil实例
     */
    public static synchronized Doc2PDFUtil getDoc2HtmlUtilInstance() {
        if (doc2HtmlUtil == null) {
            doc2HtmlUtil = new Doc2PDFUtil();
        }
        return doc2HtmlUtil;
    }

    private static void copyInputStreamToFile(InputStream inputStream, File file)
            throws IOException {

        try (FileOutputStream outputStream = new FileOutputStream(file)) {
            int read;
            byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        }
    }

    /**
     * 转换文件成pdf
     *
     * @param fromFileInputStream:
     * @throws IOException
     */
    public String fileToPDF(InputStream fromFileInputStream,String suffix) throws IOException {
        //获取随机的文件名
        String uuid = UUID.randomUUID().toString().replace("-","");
        String pdfName =TARGET_FOLDER+uuid + ".pdf";
        File targetFile = new File(pdfName);
        File originFile = new File(TARGET_FOLDER+uuid+"."+"txt");
        copyInputStreamToFile(fromFileInputStream,originFile);

        OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
        try {
            connection.connect();
            StreamOpenOfficeDocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
            converter.convert(originFile, targetFile);
        } catch (Exception e) {
            log.error("文件转换出错",e.getCause());
            throw new RuntimeException("文件转换出错");
        } finally {
            connection.disconnect();
        }
        // 转换完之后删除word文件
        originFile.delete();
        //30秒后删除文件
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(30);
            }catch (Exception ex){
                log.error("转换文件延迟删除异常");
            }finally {
                targetFile.delete();
            }
        }).start();
        return uuid + ".pdf";
    }
}
